package gameLogic

import (
	"fmt"
	"strconv"
	"time"

	"github.com/sirupsen/logrus"
	lua "github.com/yuin/gopher-lua"
)

func setLoginState(infoMap *map[string]string) {
	(*infoMap)[LoginStat] = strconv.Itoa(int(time.Now().Unix()))
}

func clearLoginState(infoMap *map[string]string) {
	delete((*infoMap), LoginStat)
}

func IsUserLogin(infoMap *map[string]string) bool {
	if _, ok := (*infoMap)[LoginStat]; ok {
		return true
	}
	return false
}

func init() {

}

func GameLogin(infoMap *map[string]string, paramsVec []string) []byte {
	if len(paramsVec) < 2 {
		return Str2bytes("param num incorect")
	}
	name := paramsVec[0]
	pwd := paramsVec[1]
	logrus.Infoln("name:", name, ", pwd:", pwd)
	if LoginImpl(name, pwd) == LoginSucc {
		if _, ok := (*infoMap)[LoginStat]; ok {
			return Str2bytes(fmt.Sprintf("user %s has been succ login.", name))
		}
		setLoginState(infoMap)
		logrus.Infoln(fmt.Sprintf("user %s has succ login.", name))
		return Str2bytes("login success")
	}

	return Str2bytes("login failed!")
}

func GameRegister(infoMap *map[string]string, paramsVec []string) []byte {
	if len(paramsVec) < 2 {
		return Str2bytes("param num incorect")
	}
	name := paramsVec[0]
	pwd := paramsVec[1]
	logrus.Infoln("name:", name, ", pwd:", pwd)
	if RegisterImpl(name, pwd) == RegisterSucc {
		setLoginState(infoMap) //注册好以后直接设置登录态
		return Str2bytes("register success! you has auto login! please input 'all' to discover the world")
	}
	return Str2bytes("register failed! please cotact admin!")
}

//主要执行游戏函数，GameExec，独立于登录&注册函数之外
//TODO 提高拓展性，可以考虑用lua来做游戏脚本，暂时不做热加载。变更配置需要重启
func GameExec(infoMap *map[string]string, paramsVec []string, vm *lua.LState) []byte {
	return Str2bytes("null")
}
